package app.demo.controller;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springleaf.utils.MD5;
import org.springleaf.utils.VerifyImage;
import org.springleaf.utils.WebHelper;

import app.demo.controller.base.UserBaseController;
import app.demo.model.Customer;
import app.demo.service.CustomerService;

/**
 * 公共Controller
 * @author leaf
 */
@Controller
@SessionAttributes
public class CommanController extends UserBaseController{

	@Resource
	private CustomerService customerService;
	
	/**
	 * 首页(如果没登陆,则跳转到登录页)
	 * @return
	 */
	@RequestMapping("index")
	public ModelAndView index(){
		Customer user = getUser();
		if(user != null){
			return redirect("/msg");
		}
		//跳到登录页面
		return render("../login");
	}
	
	/**
	 * 登录
	 * @param customer
	 * @param model
	 */
	@RequestMapping("login")
	public ModelAndView login(Customer customer) throws Exception{
		customer.setPassword(DigestUtils.md5Hex(customer.getPassword()));
		customer = customerService.login(customer);
		if(customer != null){
			setUser(customer);//设置当前用户
			return renderJson(true,"登录成功");
		}else{
			return renderJson(false,"帐号或密码错误");
		}
	}

	/**
	 * 修改密码
	 * @param oldPwd 旧密码
	 * @param newPwd 新密码
	 * @param user 当前登录的用户
	 */
	@RequestMapping("changePwd")
	public ModelAndView changePwd(String oldPwd,String newPwd,@ModelAttribute(CommanController.CURRUSER) Customer customer) throws Exception{
		if(StringUtils.isNotBlank(oldPwd) && StringUtils.isNotBlank(newPwd)){
			oldPwd = DigestUtils.md5Hex(oldPwd);
			if(oldPwd.equals(customer.getPassword())){
				newPwd = MD5.encrypt(newPwd);
				customer.setPassword(newPwd);
				customerService.update(customer);
				return renderJson(true,"用户密码修改成功");
			}
		}
		return renderJson(false,"用户密码原密码错误");
	}
	
	/**
	 * 验证码
	 */
	@ResponseBody
	@RequestMapping("verify")
	public String verify() throws Exception {
		ServletOutputStream out = WebHelper.getResp().getOutputStream();
		VerifyImage img = new VerifyImage();
		String verifyStr = img.createVerify();
		WebHelper.setHttpResponseImageHeader();
		img.createVerifyImage(verifyStr, out);
		out.close();
		log.debug("验证码:" + verifyStr);
		return null;
	}
	
	/**
	 * 退出
	 */
	@RequestMapping("logout")
	public ModelAndView logout(SessionStatus status){
		getSes().invalidate();
		status.setComplete();//销毁session
		return redirect("/index");
	}
	
}
